<?php

namespace app\admin\model;

use think\Log;
use think\Model;
use think\Db;
use think\Cache;

class Activity_conf extends Model
{


    // 表名
    protected $table = 'activity_conf';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'repeat_text',
        'meetingType_text',
        'status_text'
    ];


    public function getRepeatList()
    {
        return ['n' => __('No repetition'),
            'd' => __('Daily'),
            'w' => __('Weekly'),
            's' => __('Every two weeks'),
            'm' => __('Monthly')];
    }

    public function getdurationList($mode="null")
    {
        if ($mode == "live"){
            return ['s' => __('Short term %s',__("Live")),
//                'l' => __("Long term %s",__("Live"))
            ];
        }
        else{
            return ['s' => __('Short term %s',__(config('appWords.meeting')['en'])),
                'l' => __("Long term %s",__(config('appWords.meeting')['en']))];
        }

    }
    public function getOptionList()
    {
        return [
            'onlyParticipants' => __('Only participants %s',__(config('appWords.meeting')['en'])),
            'callParticipants' => __('%s Call participants',__(config('appWords.meeting')['en'])),
            'callEquipment' => __('%s Call equipment',__(config('appWords.meeting')['en'])),
//            'freeCamera' => __('Free Camera'),
//            'mainBroadcast' => __('Main Broadcast'),
//            'mainCamera' => __('Webinar'),
        ];
    }

    public function getMeetingtypeList()
    {
        return ['0' => __('General meeting'),
            '1' => __('Important meeting')];
    }

    public function getStatusList()
    {
        return ['0' => __('Stop it'), '1' => __('Have in hand')];
    }

    public function getisOpenList()
    {
        return ['0' => __('Close'), '1' => __('Open')];
    }

    public function getRepeatTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['repeat']) ? $data['repeat'] : '');
        $list = $this->getRepeatList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getMeetingtypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['meetingType']) ? $data['meetingType'] : '');
        $list = $this->getMeetingtypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function admin()
    {
        return $this->belongsTo('Admin', 'admin_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function getCompanyUsersList($company_id)
    {
        static $allUsersId = [];
        if ($company_id) {
            $companyUsersId = Db::query("select id,nickname from admin where company_id=?", [$company_id]);
            foreach ($companyUsersId as $row) {
                $allUsersId[$row['id']] = $row['nickname'];
            }
            return $allUsersId;
        }
        return $allUsersId;
    }

    public function getCompanyFiles($company_id)
    {
        //资料相关
        if ($company_id) {
            $thisCompanyfile = Db::table('confdoc')->where('company_id', $company_id)->select();
            $confFileLists = [];
            foreach ($thisCompanyfile as $val) {
                if ($val['source_type'] != 'image') {
                    $confFileLists[$val['id']] = $val['source_name'];
                } else {
                    $confFileLists[$val['id']] = $val['name'];
                }
            }
            return $confFileLists;
        }
        return null;
    }

    public function getCompanyEquipment($company_id)
    {
        //设备相关
        $allUsers = [];
//        $thisUserCompany = Db::query("select * from auth_company where uid=?",[$company_id]);
        if ($company_id) {
            $companyUsers = Db::query("select id from admin where company_id=?", [$company_id]);
            foreach ($companyUsers as $row) {
                $allUsers[] = $row['id'];
            }
            $thisCompanyfile = Db::table('equipment')->where('admin_id', 'in', $allUsers)->select();
            $confFileLists = [];
            foreach ($thisCompanyfile as $val) {
                $confFileLists[$val['id']] = $val['confRoom']."(".$val['serialNumber'].")";
            }
            return $confFileLists;
        }
        return null;
    }
    // 会议
    public function getHeadingList($admin_id,$mode=null)
    {
        $ret = [
            0 => [
                'name' => 'index',
                'head' =>  __('Future %s',__(config('appWords.meeting')['en']))
            ],
            1 => [
                'name' => 'previous',
                'head' => __('Past %s',__(config('appWords.meeting')['en']))
            ],
            2 => [
                'name' => 'myself',
                'head' => __('Myself %s',__(config('appWords.meeting')['en']))
            ]
        ];
        if ($admin_id) {
            $ret = [
                0 => [
                    'name' => 'index',
                    'head' => __('Future %s',__(config('appWords.meeting')['en']))
                ],
                1 => [
                    'name' => 'previous',
                    'head' => __('Past %s',__(config('appWords.meeting')['en']))
                ],
            ];
        }
        if ($mode){
            if ($mode == "intercom"){
                $ret = [
                    0 => [
                        'name' => 'intercom',
                        'head' => __('Future %s',__(config('Intercom mode meeting')))
                    ],
                    1 => [
                        'name' => 'intercomfuture',
                        'head' => __('Past %s',__(config('Intercom mode meeting')))
                    ],
                ];
            }
            elseif ($mode == "webinar"){
                $ret = [
                    0 => [
                        'name' => 'webinar',
                        'head' => __('Future %s',__(config('Webinar')))
                    ],
                    1 => [
                        'name' => 'webinarfuture',
                        'head' => __('Past %s',__(config('Webinar')))
                    ],
                ];
            }
            elseif ($mode == "ehsfield"){
                $ret = [
                    0 => [
                        'name' => 'ehsfield',
                        'head' => __('Future %s',__(config('EHS field operation')))
                    ],
                    1 => [
                        'name' => 'ehsfieldfuture',
                        'head' => __('Past %s',__(config('EHS field operation')))
                    ],
                ];
            }
            elseif ($mode == "multilingual"){
                $ret = [
                    0 => [
                        'name' => 'multilingual',
                        'head' => __('Future %s',__(config('Multilingual translation')))
                    ],
                    1 => [
                        'name' => 'multilingualfuture',
                        'head' => __('Past %s',__(config('Multilingual translation')))
                    ],
                ];
            }
            elseif ($mode == "voice"){
                $ret = [
                    0 => [
                        'name' => 'voice',
                        'head' => __('Future %s',__(config('appWords.meeting')))
                    ],
                    1 => [
                        'name' => 'voicefuture',
                        'head' => __('Past %s',__(config('appWords.meeting')))
                    ],
                ];
            }else{
                return $ret;
            }
        }
        return $ret;
    }

    // 会议
    public function getManageHeadingList($admin_id)
    {
        $ret = [
            0 => [
                'name' => 'manage',
                'head' => __('Management of %s',__(config('appWords.meeting')['en']))
            ],
            1 => [
                'name' => 'manage?paystatus=paid',
                'head' => __('Paid %s',__(config('appWords.conf_room')['en']))
            ],
            2 => [
                'name' => 'manage?paystatus=payable',
                'head' => __('Payable %s',__(config('appWords.conf_room')['en']))
            ],
            3 => [
                'name' => 'manage?paystatus=unpaid',
                'head' => __('Paystatus %s',__(config('appWords.conf_room')['en']))
            ],
            4 => [
                'name' => 'forthcoming',
                'head' => __('Soon to convene')
            ],
            5 => [
                'name' => 'past',
                'head' => __('Past times %s',__(config('appWords.meeting')['en']))
            ],
            6 => [
                'name' => 'duplicate',
                'head' => __('Repeat  %s',__(config('appWords.meeting')['en']))
            ],
            7 => [
                'name' => 'personal',
                'head' => __("User's Personal %s",__(config('appWords.conf_room')['en']))
            ],
            8 => [
                'name' => 'running',
                'head' => __("Online %s",__(config('appWords.conf_room')['en']))
            ],
        ];

        return $ret;
    }

    public function getModeList()
    {
        $modeList = [
            'freeCamera' => __('Free Camera'),
            'mainBroadcast' => __('Webcast Conference'),
            'mainCamera' => __('Webinar'),
//            'intercom' => __('Intercom mode meeting'),
//            'EHSfieldOperation' => __('EHS field operation'),
//            'voiceSeminar' => __('Voice Conference'),
//            'trainingConference' => __('Online Training Conference'),
//            'multilingualTranslation' => __('Multilingual translation'),
//            'videomarketing' => __('Video marketing customer service'),
        ];
        $confmode = config("confModeSwitches");
        $newData = array();
        foreach ($confmode as $item=>$val) {
            if ($val){
                if (isset($modeList[$item])){
                    $newData[$item] = $modeList[$item];
                }
            }
        }
        return $newData;
    }

    public function getHoursList()
    {
        $hoursList = array();
        for ($i = 0; $i < 24; $i++) {
            $hoursList[$i] = $i;
        }
        $hoursList[24] = 24;
        $hoursList[48] = 48;
        $hoursList[72] = 72;
        $hoursList[168] = 168;
        $hoursList[360] = 360;
        $hoursList[720] = 720;
        return $hoursList;
    }

    public function getMinutesList()
    {
        $hoursList = array();
        for ($i = 0; $i < 60; $i++) {
            $hoursList[$i] = $i;
        }
        return $hoursList;
    }

    // 获取加密地址
    public function getEncryptedExtranet($cid, $host, $scheme){
        // 获取缓存中的剩余服务器

        $user = Db::name('admin')->alias('admin')
            ->join("conference conf","conf.admin_id=admin.id")
            ->where("conf.serial",$cid)
            ->find();
        if (!$user['admin_tag']){
            $user['admin_tag'] = "null";
            $user['validity_time'] = "2000-01-01 00:00:00";
        }
//        $now = date("Y-m-d H:i:s", time());
//        if (strtotime($user['validity_time']) < strtotime((string)$now)){
//            $user['admin_tag'] = 1;
//        }
        $cacheType = config('cache.redis') ? 'redis' : '';
//        $allServerAddress = Cache::store($cacheType)->get(config('redis_prefix').'ServerAddress');
        $allServerAddress = Cache::store($cacheType)->get(config('redis_prefix').'ServerAddress'."-admin_tag-".$user['admin_tag']);
        if (!$allServerAddress) {
            $serverAddressObj = new \app\admin\model\ServerAddress;
            $allServerAddress = [];
//            $serverAddressSQLdata = $serverAddressObj->select();
            $user_tags_service = Db::name('server_grouping')->whereLike("tag_ids",'%'.$user['admin_tag'].'%')->find();

            $serverAddressSQLdata = $serverAddressObj->where("distinguish",$user_tags_service['id'])->select();
            if (!$serverAddressSQLdata){
                $serverAddressSQLdata = $serverAddressObj->where('distinguish is null')->select();
            }
            foreach ($serverAddressSQLdata as $sqldata) {
                $addressInfo = [];
                $addressInfo["intranet_address"] = $sqldata['intranet_address'];
                $addressInfo["external_address"] = $sqldata["external_address"];
                $addressInfo["encrypted_extranet"] = $sqldata["encrypted_extranet"];
                $addressInfo["encrypted_intrane"] = $sqldata["encrypted_intrane"];
                $allServerAddress[] = $addressInfo;
            }
        }
        // 查询会议ID是否已分配会议地址
        $ConfServerAddress = Cache::store($cacheType)->get(config('redis_prefix').'ConfServerAddress:' . $cid);
        if ($ConfServerAddress) {
            $seradd = $ConfServerAddress;
        } else {
            $seradd = array_shift($allServerAddress);
            Cache::store($cacheType)->set(config('redis_prefix').'ConfServerAddress:' . $cid, $seradd, 0);
            Cache::store($cacheType)->set(config('redis_prefix').'ServerAddress'."-admin_tag-".$user['admin_tag'], $allServerAddress, 0);
        }
        if ($scheme == "https") {
            $encrypted = 1;
        } elseif ($scheme == "http") {
            $encrypted = 0;
        } else {
            $encrypted = 1;
        }
        if ($encrypted) {
            $encryptedIntrane = explode(":", $seradd['encrypted_intrane']);
            $encryptedIntrane = $encryptedIntrane[1];
            $encryptedIntrane = explode("//", $encryptedIntrane);
            $encryptedIntrane = $encryptedIntrane[1];

            $encryptedExtranet = explode(":", $seradd['encrypted_extranet']);
            $encryptedExtranet = $encryptedExtranet[1];
            $encryptedExtranet = explode("//", $encryptedExtranet);
            $encryptedExtranet = $encryptedExtranet[1];
            if ($host == $encryptedExtranet) {
                $addressInfo = $seradd['encrypted_extranet'];
            } elseif ($host == $encryptedIntrane) {
                $addressInfo = $seradd['encrypted_intrane'];
            } else {
                $addressInfo = $seradd['encrypted_extranet'];
            }
        } // 不加密
        else {
            $intranetAddress = explode(":", $seradd['intranet_address']);
            $intranetAddress = $intranetAddress[1];
            $intranetAddress = explode("//", $intranetAddress);
            $intranetAddress = $intranetAddress[1];

            $externalAddress = explode(":", $seradd['external_address']);
            $externalAddress = $externalAddress[1];
            $externalAddress = explode("//", $externalAddress);
            $externalAddress = $externalAddress[1];

            if ($host == $intranetAddress) {
                $addressInfo = $seradd['intranet_address'];
            } elseif ($host == $externalAddress) {
                $addressInfo = $seradd['external_address'];
            } else {
                $addressInfo = $seradd['external_address'];
            }
        }
//        $encrypted_extranet = trim($seradd['encrypted_extranet'], '/').'/';
        $encrypted_extranet = trim($addressInfo, '/').'/';

        return $encrypted_extranet;
    }


    public function getDepartmentList($company_id)
    {
        static $allDepartment = [];
        if ($company_id) {
            $companyUsersId = Db::name("department")
                ->where('company_id',$company_id)
                ->select();
            foreach ($companyUsersId as $row) {
                $allDepartment[$row['id']] = $row['name'];
            }
            return $allDepartment;
        }
        return $allDepartment;
    }

    public function getIsEoc($usertype)
    {

        if ($usertype == 3) {
            return 0;
        }
        return 1;
    }


    public function getModeHeadList($mode)
    {
        if ($mode){
            if ($mode == "intercom"){
                $ret = [
                    0 => [
                        'name' => 'intercom',
                        'head' => __('Future %s',__('Intercom mode meeting'))
                    ],
                    1 => [
                        'name' => 'intercomfuture',
                        'head' => __('Past %s',__('Intercom mode meeting'))
                    ],
                ];
            }
            elseif ($mode == "mainCamera"){
                $ret = [
                    0 => [
                        'name' => 'webinar',
                        'head' => __('Future %s',__('Webinar'))
                    ],
                    1 => [
                        'name' => 'webinarfuture',
                        'head' => __('Past %s',__('Webinar'))
                    ],
                ];
            }
            elseif ($mode == "EHSfieldOperation"){
                $ret = [
                    0 => [
                        'name' => 'ehsfield',
                        'head' => __('Future %s',__('EHS field operation'))
                    ],
                    1 => [
                        'name' => 'ehsfieldfuture',
                        'head' => __('Past %s',__('EHS field operation'))
                    ],
                ];
            }
            elseif ($mode == "multilingualTranslation"){
                $ret = [
                    0 => [
                        'name' => 'multilingual',
                        'head' => __('Future %s',__('Multilingual translation'))
                    ],
                    1 => [
                        'name' => 'multilingualfuture',
                        'head' => __('Past %s',__('Multilingual translation'))
                    ],
                ];
            }
            elseif ($mode == "voiceSeminar"){
                $ret = [
                    0 => [
                        'name' => 'voice',
                        'head' => __('Future %s',__('Voice Conference'))
                    ],
                    1 => [
                        'name' => 'voicefuture',
                        'head' => __('Past %s',__('Voice Conference'))
                    ],
                ];
            }
            elseif ($mode == "videomarketing"){
                $ret = [
                    0 => [
                        'name' => 'marketing',
                        'head' => __('Future %s',__('Video marketing customer service'))
                    ],
                    1 => [
                        'name' => 'marketingfuture',
                        'head' => __('Past %s',__('Video marketing customer service'))
                    ],
                ];
            }
            elseif ($mode == "mainBroadcast"){
                $ret = [
                    0 => [
                        'name' => 'webcast',
                        'head' => __('Future %s',__('Webcast Conference'))
                    ],
                    1 => [
                        'name' => 'webcastfuture',
                        'head' => __('Past %s',__('Webcast Conference'))
                    ],
                ];
            }
        }
        return $ret;
    }

    public function getLiveHeadingList()
    {
        $ret = [
            0 => [
                'name' => 'liveindex',
                'head' =>  __('Future %s',__("Live"))
            ],
            1 => [
                'name' => 'liveprevious',
                'head' => __('Past %s',__("Live"))
            ],
        ];
        return $ret;
    }

    /* 
     * 获取后台永不失效的token用于后台分享使用的链接之中
     */
    public function getUserToken($user_id, $token) {
        $info = Db::name('user_token')
            ->where(['user_id'=>$user_id, 'expiretime'=>0])
            ->field('tokenbu')
            ->find();

        if (empty($info)) {
            // 没有获取到永不失效的token，可能是执行过登出所有设备或更新后暂未重新登录
            $config = \think\Config::get('token');
            $encryptedToken = hash_hmac($config['hashalgo'], $token, $config['key']);
            Db::name('user_token')->insert([
                'token'      => $encryptedToken,
                'user_id'    => $user_id,
                'createtime' => time(),
                'expiretime' => 0,
                'tokenbu'    => $token
            ]);

            return $token;
        }else{
            return $info['tokenbu'];
        }
    }

    /* 
     * 获取当前公司已绑定终端的大屏列表
     */
    public function getCompanyScreen($company_id) {
        $list = Db::name('screen')
            ->where(['company_id'=>$company_id, 'isdel'=>0])
            ->where('terminal_count', '<>', 0)
            ->field('id, name')->select();

        $data = [];
        if (!empty($list)) {
            foreach ($list as $key => $value) {
                $data[$value['id']] = $value['name'];
            }
        }

        return $data;
    }
    public function repeatTime()
    {
        return [
            'd' => array('text'=>"每天的会议时长不能超过24小时","number"=>1),
            'w' => array('text'=>"每周的会议时长不能超过".strval(7*24)."小时","number"=>7),
            's' => array('text'=>"每两周的会议时长不能超过".strval(14*24)."小时","number"=>14),
            'm' => array('text'=>"每月的会议时长不能超过".strval(30*24)."小时","number"=>30)
        ];
    }

    // 高级会议
    public function getModeHeadingList($mode=null)
    {
        $ret = array();
        $modes = Db::name('advanced_mode')->where('mode',$mode)->select();
        foreach ($modes as $item) {
            $info = array(
                "name" => $mode."?id=".$item['id'],
                'head' => $item['name']
            );
            $ret[] = $info;
        }
        return $ret;
    }
}
